package dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import pojo.Merchant;
import dao.MerchantDao;

@Repository(value="merchantDao")
public class MerchantDaoImpl extends BaseDaoImpl<Merchant> implements MerchantDao{

	@PersistenceContext(name="un")
	private EntityManager manager;
	
	@Override
	public Merchant add(Merchant t) {
		manager.persist(t);
		return t;
	}

	@Override
	public Merchant delete(String id) {
		return null;
	}

	@Override
	public Merchant update(Merchant t) {
		return null;
	}

	@Override
	public Merchant load(String id) {
		return null;
	}

	@Override
	public List<Merchant> findAll() {
		String jpql = "SELECT m FROM Merchant m";
		List<Merchant> merchants = manager.createQuery(jpql).getResultList();
		return merchants;
	}

	@Override
	public Merchant updateStatusByName(String name, String status) {
		String jpql = "SELECT m FROM Merchant m WHERE m.name=:name";
		List<Merchant> merchants = manager.createQuery(jpql)
				.setParameter("name", name)
				.getResultList();
		if(merchants.size() > 0){
			merchants.get(0).setStatus(status);
			manager.merge(merchants.get(0));
			return merchants.get(0);
		}
		return null;
	}

	@Override
	public List<Merchant> getByName(String name) {
		String jpql = "SELECT m FROM Merchant m WHERE m.name=:name";
		List<Merchant> merchants = manager.createQuery(jpql)
				.setParameter("name", name)
				.getResultList();
		if(merchants.size() > 0)
			return merchants;
		return null;
	}

	@Override
	public List<Merchant> findByStatus(String status) {
		String jpql = "SELECT m FROM Merchant m WHERE m.status=:status";
		List<Merchant> merchants = manager.createQuery(jpql)
				.setParameter("status", status)
				.getResultList();
		return merchants;
	}

	@Override
	public Merchant updateByName(Merchant merchant) {
		String jpql = "SELECT m FROM Merchant m WHERE m.name=:name";
		List<Merchant> merchants = manager.createQuery(jpql)
				.setParameter("name", merchant.getName())
				.getResultList();
		if(merchants.size() > 0){
			merchants.get(0).setIdCard(merchant.getIdCard());
			merchants.get(0).setAvatar(merchant.getAvatar());
			merchants.get(0).setAddress(merchant.getAddress());
			merchants.get(0).setStatus(merchant.getStatus());
			merchants.get(0).setRejectReason(merchant.getRejectReason());
			merchants.get(0).setUpdateTime(merchant.getUpdateTime());
			return merchants.get(0);
		}
		return null;
	}
	
	
}
